package com.wbao.dianniu.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.login.YWLoginState;
import com.alibaba.mobileim.utility.IMAutoLoginInfoStoreUtil;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.im.NotificationInitSampleHelper;
import com.wbao.dianniu.im.UserProfileSampleHelper;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.manager.LoginManager;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;


public class SplashActivity extends Activity implements ILoginListener {
    private LinearLayout imageLayout;
    private LoginManager manager;
    boolean isFirstIn = false;
    protected static final String TAG = LoginActivity.class.getSimpleName();
    private String type = null;
    private String id = null;

    /*private BroadcastReceiver mAutoLoginStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final int state = intent.getIntExtra("state", -1);
            YWLog.i(TAG, "mAutoLoginStateReceiver, loginState = " + state);
            if (state == -1) {
                return;
            }
            handleAutoLoginState(state);
        }
    };*/

    private void init(String userId, String appKey) {
        final String hisUserId = IMAutoLoginInfoStoreUtil.getLoginUserId();
        if (!hisUserId.equals(userId) && !hisUserId.isEmpty()) {    // 两次登录用户不同 先调用登出命令再调用登录命令
            LoginSampleHelper.getInstance().loginOut_Sample();
        }
        //初始化imkit
        LoginSampleHelper.getInstance().initIMKit(userId, appKey);
        //自定义头像和昵称回调初始化(如果不需要自定义头像和昵称，则可以省去)
        UserProfileSampleHelper.initProfileCallback();
        //通知栏相关的初始化
        NotificationInitSampleHelper.init();
    }

    /*private void handleAutoLoginState(int loginState) {
        if (loginState == YWLoginState.logining.getValue()) {
        } else if (loginState == YWLoginState.success.getValue()) {
            Intent intent = new Intent();
            if (null != type && null != id) {
                intent.putExtra(GlobalContext.INTENT_SCHEME_TYPE, type);
                intent.putExtra(GlobalContext.INTENT_SCHEME_ID, id);
            }
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.setClass(SplashActivity.this, MainActivity.class);
            SplashActivity.this.startActivity(intent);
            SplashActivity.this.finish();
        }
    }*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //取消标题栏
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //取消状态栏
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);
        imageLayout = (LinearLayout) findViewById(R.id.splash_layout);
        // 判断是否是从网页跳转的，如果是从网页跳转的，直接跳转到对应界面
        Intent intent = getIntent();
        String scheme = intent.getScheme();
        if (null != scheme) {
            if (scheme.equals("dianniu")) {
                Uri uri = intent.getData();
                if (uri != null) {
                    String host = uri.getHost();
                    String dataString = intent.getDataString();
                    //获得参数值
                    type = Utils.getQueryParam(dataString, "shareType");
                    id = Utils.getQueryParam(dataString, "id");
                    // 解析type
                }
            }
        }
        /*BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        int screenMax = Math.max(
                DensityUtils.getWindowWidth(this),
                DensityUtils.getWindowHeight(this));
        int imgMax = Math.max(opts.outWidth, opts.outHeight);
        int inSimpleSize = 1;
        if (screenMax <= imgMax) {
            inSimpleSize = Math.round(Math.max(screenMax, imgMax)
                    / Math.min(screenMax, imgMax));
        }
        opts.inSampleSize = inSimpleSize;
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.splash, opts);*/
//        imageLayout.setBackgroundResource(R.drawable.splash);

        // 定时器
        Handler handler = new Handler();
        //获取自动登录状态
        SharedPreferencesUtils.init(this);
        boolean auto_status = SharedPreferencesUtils.getAutoLoginStatus(this);
        String username = SharedPreferencesUtils.getUserName();
        String password = SharedPreferencesUtils.getPassword();
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            SharedPreferencesUtils.setAutoLoginStatus(false);
            auto_status = false;
        }
        // 判断网络是否可用，不可用，直接到登录界面
        boolean net = Utils.isNetworkAvaiable(this);
        if (!net) {
            auto_status = false;
            Notification.toast(this, "网络不可用，请检测网络");
        }

        //------------这个为兼容性测试所用-------------------
//        auto_status = true;
//        username = "13900000006";
//        password = Utils.Md5("123456");
        //------------------------------------------------

        if (auto_status) {    //自动登录
            //获取用户名和密码 自动登录
            manager = new LoginManager(this);
            manager.addLoginListener(this);
            /**  这里做兼容性 -- 1.2版本的用户保存的是明文的密码，自动更新后，自动登录会提示用户名密码错，需要先加密再请求登录  */
            if (password.length() != 32) {// 把32位密码默认为已经加密的密码
                password = Utils.Md5(password);
            }
            manager.Login(this, username, password, Utils.getDeviceId(this), null, null, Utils.getVersionName(this), null);
        } else {
            handler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    startActivity(new Intent(SplashActivity.this, LoginActivity.class));
                    SplashActivity.this.finish();
                }
            }, 1 * 1000);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != manager) {
            manager.removeLoginListener(this);
        }
//        myUnregisterReceiver();
    }


//    private void myRegisterReceiver() {
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(AUTO_LOGIN_STATE_ACTION);
//        LocalBroadcastManager.getInstance(YWChannel.getApplication()).registerReceiver(mAutoLoginStateReceiver, filter);
//    }

//    private void myUnregisterReceiver() {
//        LocalBroadcastManager.getInstance(YWChannel.getApplication()).unregisterReceiver(mAutoLoginStateReceiver);
//    }

    @Override
    public void onLoginFailure(int errorCode, String errorMsg) {
        // TODO Auto-generated method stub
        startActivity(new Intent(SplashActivity.this, LoginActivity.class));
        finish();
    }

    @Override
    public void onLoginSuccess(LoginResponse objdata) {
        // TODO Auto-generated method stub
        Utils.saveLoginData(this, objdata);
        init(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), getResources().getString(R.string.app_key));
//        myRegisterReceiver();
        //登录成功时，登录IM
        loginIM(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), objdata.getAccountInfo().getPwd());
    }

    public void loginIM(String userId, String password) {
        // 调用登录IM代码，不对登录结果做处理，先登录到主界面
        if (null == LoginSampleHelper.getInstance().getIMKit()) {
            //初始化imik
            LoginSampleHelper.getInstance().initIMKit(userId, getResources().getString(R.string.app_key));
        }
        IYWLoginService loginService = LoginSampleHelper.getInstance().getIMKit().getLoginService();
        YWLoginParam loginParam = YWLoginParam.createLoginParam(userId, password);
        loginService.login(loginParam, new IWxCallback() {
            @Override
            public void onSuccess(Object... objects) {
                // 成功 界面跳转
                Intent intent = new Intent();
                if (null != type && null != id) {
                    intent.putExtra(Const.INTENT_SCHEME_TYPE, type);
                    intent.putExtra(Const.INTENT_SCHEME_ID, id);
                }
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.setClass(SplashActivity.this, MainActivity.class);
                startActivity(intent);
                SplashActivity.this.finish();
            }

            @Override
            public void onError(int errCode, String description) {
                //如果登录失败，errCode为错误码,description是错误的具体描述信息
               /* if (null != description) {
                    Notification.toast(SplashActivity.this, description);
                } else {
                    Notification.toast(SplashActivity.this, "【登录失败，错误码】：" + errCode);
                }*/
                startActivity(new Intent(SplashActivity.this, LoginActivity.class));
                finish();
            }

            @Override
            public void onProgress(int i) {

            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }


}

